<div id="paypal-google-container-{{pay_id}}" style="width: 100%;height: 48px;"></div>
<script src="https://pay.google.com/gp/p/js/pay.js"></script>

<script>
  $(function () {

    let paymentsClient = null, googlepayConfig = null;

    async function getGooglePayConfig() {
      if (googlepayConfig === null) {
        googlepayConfig = await paypal.Googlepay().config();
        console.log(" ===== Google Pay Config Fetched ===== ");

      }
      return googlepayConfig;
    }

    async function getGooglePaymentDataRequest() {
      const { allowedPaymentMethods, merchantInfo, apiVersion, apiVersionMinor, countryCode } = await getGooglePayConfig();
      const baseRequest = {
        apiVersion,
        apiVersionMinor
      }
      const paymentDataRequest = Object.assign({}, baseRequest);

      paymentDataRequest.allowedPaymentMethods = allowedPaymentMethods;
      paymentDataRequest.transactionInfo = getGoogleTransactionInfo(countryCode);
      paymentDataRequest.merchantInfo = merchantInfo;
      paymentDataRequest.shippingAddressRequired = true;
      paymentDataRequest.emailRequired = true;
      paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
      console.log('getGooglePaymentDataRequest', paymentDataRequest);
      return paymentDataRequest;
    }

    function onPaymentAuthorized(paymentData) {
      console.log('onPaymentAuthorized', paymentData);
      return new Promise(function (resolve, reject) {
        processPayment(paymentData)
          .then(function () {
            resolve({ transactionState: 'SUCCESS' });
          })
          .catch(function () {
            resolve({ transactionState: 'ERROR' });
          });
      });
    }

    function getGooglePaymentsClient() {
      if (paymentsClient === null) {
        paymentsClient = new google.payments.api.PaymentsClient({
          {% if payment.interface_type_param.api_is_test == '1' %}
            environment: 'TEST',
          {% else %}
            environment: 'PRODUCTION',
          {% endif %}
          paymentDataCallbacks: {
            onPaymentAuthorized: onPaymentAuthorized
          }
        });
      }
      return paymentsClient;
    }

    async function onGooglePayLoaded() {
      const paymentsClient = getGooglePaymentsClient();
      const { allowedPaymentMethods, apiVersion, apiVersionMinor } = await getGooglePayConfig();
      paymentsClient.isReadyToPay({ allowedPaymentMethods, apiVersion, apiVersionMinor })
        .then(function (response) {
          if (response.result) {
            addGooglePayButton();
          }
        })
        .catch(function (err) {
          // show error in developer console for debugging
          console.error(err);
        });
    }


    function addGooglePayButton() {
      const paymentsClient = getGooglePaymentsClient();
      const button =
        paymentsClient.createButton({
          buttonColor: 'default',
          buttonType: 'checkout',
          buttonSizeMode: 'fill',
          onClick: onGooglePaymentButtonClicked
        });
      document.getElementById('paypal-google-container-{{pay_id}}').appendChild(button);
    }


    function getGoogleTransactionInfo(countryCode) {
      // var params = moi.getPageStorage('product_params{{ pay_id }}');
      // let amount = Number(params.price).times(params.quantity)

      var amount = 0;
      var paypalecRet = moi.onEvent("paypalec_multiple_callback",{ payId: "{{pay_id | default :'0'}}", code: 0});
      var params = moi.getPageStorage('product_params' +{{pay_id}});
      if(!paypalecRet.params.code){
        amount = formatMoney(Number(params.price).times(params.quantity),_GET_C_SETTING_("currency"),'',false,false).toString()
      }else{
        var price = paypalecRet.params.data
          .filter((item) => item.add_quantity)
          .map((item) => parseFloat(item.price).times(item.add_quantity))
          .reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
        amount =  formatMoney(price, _GET_C_SETTING_("currency"),'',false,false).toString()
      }

      return {
        countryCode: countryCode,
        currencyCode: _GET_C_SETTING_("currency").standard_code,
        totalPriceStatus: "FINAL",
        totalPrice: amount,
        totalPriceLabel: "Total"
      };
    }
    async function onGooglePaymentButtonClicked() {
      var paypalecRet = moi.onEvent("paypalec_multiple_callback",{ payId: "{{pay_id | default :'0'}}", code: 0});
      var params = moi.getPageStorage('product_params' +{{pay_id}});
      if(!paypalecRet.params.code){
        moi.onEvent("paypalec_callback",{ payId: "{{pay_id | default :'0'}}"})
        var ret = moi.onEvent("payVerified", { property: [],product: params, code: 200 });
        if (ret.params.code !== 200) {
          return false
        }
      
      }else{
        if(paypalecRet.params.code !== 200){
          return false
        }
      }
      const paymentDataRequest = await getGooglePaymentDataRequest();
      const paymentsClient = getGooglePaymentsClient();
      console.log('onGooglePaymentButtonClicked', paymentDataRequest);
      paymentsClient.loadPaymentData(paymentDataRequest);
    }


    function getProductCartParam() {
      var product_cart_param = "";
      var paypalecRet = moi.onEvent("paypalec_multiple_callback",{ payId: "{{pay_id | default :'0'}}", code: 0});
      var params = moi.getPageStorage('product_params' +{{pay_id}});
      if(!paypalecRet.params.code){
        moi.onEvent("paypalec_callback",{ payId: "{{pay_id | default :'0'}}"})
        var ret = moi.onEvent("payVerified", { property: [],product: params, code: 200 });
        if (ret.params.code !== 200) {
          return false
        }
        var product_selected = {
              product_id: params.product_id,
              sku_code: params.sku_code,
              quantity: params.quantity,
              data_from: moi.getUrlParam("data_from") || "{{data_from}}",
              property: ret.params.property

          }
        product_cart_param = encodeURIComponent(JSON.stringify(product_selected));
      }else{
        if(paypalecRet.params.code !== 200){
          return false
        }
        const cart_param = paypalecRet.params.data.map(el=>{
          return {
            product_id: params.product_id,
            sku_code: el.sku_code,
            quantity: el.add_quantity,
            data_from: moi.getUrlParam("data_from") || "{{data_from}}",
            property: []
          }
        })
        product_cart_param = encodeURIComponent(JSON.stringify(cart_param));
      }

      return product_cart_param;
    }

    async function processPayment(paymentData) {
      console.log('processPayment', paymentData);
      try {
        const { data } = await fetch('/checkouts/ecpayment/{{payment.interface_type}}/ECPay?is_ajax=1&payment_methods=google&payment_id={{ payment.id }}&cart_param=' + getProductCartParam() + '&_ref=' + window.location.href, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        }).then((res) => res.json());
        console.log(" ===== Order Created ===== ");
        /** Approve Payment */

        const { status } = await paypal.Googlepay().confirmOrder({
          orderId: data.id,
          paymentMethodData: paymentData.paymentMethodData,
          shippingAddress: paymentData.shippingAddress,
          email: paymentData.email,
        });


        console.log(" ===== confirmOrder status ===== ", status)

        if (status === 'PAYER_ACTION_REQUIRED') {
          console.log(" ===== Confirm Payment Completed Payer Action Required ===== ")
          paypal.Googlepay().initiatePayerAction({ orderId: data.id }).then(async () => {
            location.href = data.return_url;
          })
        }
        else if (status === 'APPROVED') {
          location.href = data.return_url; return;
        } else {
          moi.message({ content: data.L_LONGMESSAGE0, type: "error" });
        }

        return { transactionState: 'SUCCESS' }


      } catch (err) {
        moi.message({ content: err, type: "error" });
        return {
          transactionState: 'ERROR',
          error: {
            message: err.message
          }
        }
      }
    }

    if (window["google"] && paypal.Googlepay) {
      onGooglePayLoaded().catch(console.log);
    }
  })
</script>